/* eslint-disable no-param-reassign */
const express = require("express");
const bodyParser = require("body-parser");
//const axios = require("axios");
const fs = require('fs');
const path = require('path');

const app = express();

const WEATHER_FILE = path.join(__dirname, 'weather.json');

app.set("port", process.env.PORT || 3000);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req, res, next) => {
    res.setHeader(
        "Cache-Control",
        "no-cache, no-store, must-revalidate"
    );
    res.setHeader("Pragma", "no-cache");
    res.setHeader("Expires", "0");
    next();
});

app.get('/products', (req, res) => {
    fs.readFile(WEATHER_FILE, (err, data) => {
        console.log(data);
        res.setHeader('Cache-Control', 'no-cache');
        res.json(JSON.parse(data));
    });
});

app.get("/weather", (req, res) => {
    const id = req.query.id;
    console.log(id);

    fs.readFile(WEATHER_FILE, (err, data) => {
        weathers = JSON.parse(data)
        //console.log(weathers);
        weather = weathers.filter((wea) => wea.id === id)
        console.log(weather[0]);
        res.setHeader('Cache-Control', 'no-cache');
        res.json(weather[0]);
    });

});

app.listen(app.get("port"), () => {
    console.log( // eslint-disable-line no-console
        `Find the server at: http://localhost:${app.get(
            "port"
        )}/`
    );
});
